#pragma once
#include <iostream>
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <unistd.h>
#include <cerrno>
#include <cstring>

#define PATHNAME "."
#define PROJ_ID 0x66
#define MAX_SIZE 4096

key_t getKey()
{
    key_t k = ftok(PATHNAME, PROJ_ID);
    if (k < 0)
    {
        std::cerr << "ftok" << errno << strerror(errno) << std::endl;
        exit(1);
    }
    return k;
}

int getShmHelper(key_t key, int flages)
{
    int shmid = shmget(key, MAX_SIZE, flages);
    if (shmid < 0)
    {
        std::cerr << "shmget" << errno << strerror(errno) << std::endl;
        exit(2);
    }
    return shmid;
}

int getShm(key_t key)
{
    return getShmHelper(key, IPC_CREAT);
}

int createShm(key_t key)
{
    return getShmHelper(key, IPC_CREAT | IPC_EXCL | 0600);
}

void *attachShm(int shmid)
{
    void *mem = shmat(shmid, nullptr, 0);
    if ((long long)mem == -1)
    {
        std::cerr << "shmat" << errno << strerror(errno) << std::endl;
    }
}

void detachShm(void *shart)
{
    if (shmdt(shart) == -1)
    {
        std::cerr << "shmdt: " << errno << ":" << strerror(errno) << std::endl;
    }
}

void delShm(int shmid)
{
    if (shmctl(shmid, IPC_RMID, nullptr) == -1)
    {
        std::cerr << "shmctl: " << errno << ":" << strerror(errno) << std::endl;
    }
}